package work.linruchang.cmd;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * @author LinRuChang
 * @version 1.0
 * @date 2023/03/27
 * @since 1.8
 **/
public class CMDFactory {

    public static final String WINDOWS = "WINDOWS";
    public static final String LINUX = "LINUX";


    private static Map<String,CMD> systemNameToCMDMap = Collections.synchronizedMap(MapUtil.newHashMap());
    static {
        Set<Class<?>> CMDClasses = ClassUtil.scanPackageBySuper(null, CMD.class);
        CMDClasses.stream()
                .forEach(CMDClass -> {
                    String systemName = AnnotationUtil.getAnnotationValue(CMDClass, Resource::name);
                    CMD cmd = Convert.convert(CMD.class, ReflectUtil.newInstance(CMDClass));
                    systemNameToCMDMap.put(systemName,cmd);
                });

    }


    public static CMD getCMD() {
        OsInfo osInfo = SystemUtil.getOsInfo();
        if(osInfo.isWindows()) {
            return systemNameToCMDMap.get(CMDFactory.WINDOWS);
        }else if (osInfo.isLinux()) {
            return systemNameToCMDMap.get(CMDFactory.LINUX);
        }else {
            throw new RuntimeException(StrUtil.format("不支持当前系统【{}】，当前仅支持Linux以及Windows系统", osInfo.getName()));
        }
    }

}
